package com.xique.park.command.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.api.IParkIpcCommandApi;
import com.xique.park.command.handler.base.BaseCommand;
import com.xique.park.constant.CommandConstant;
import com.xique.park.constant.ParkApiName;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author shd
 * @create 2022/7/4 10:45
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class UnlicensedCarInHandler extends BaseCommand {

    /**
     * 车牌
     */
    private final ThreadLocal<String> plate = new ThreadLocal<>();

    /**
     * 订单序列号
     */
    private final ThreadLocal<String> parkingSerial = new ThreadLocal<>();

    private final IParkIpcCommandApi parkIpcCommandApi;

    @Override
    public String getServiceName() {
        return ParkApiName.COMMAND_MARK_UNLICENSED_CAR_IN;
    }

    @Override
    public String getVersion() {
        return ParkApiName.VER_3_0;
    }

    @Override
    public AjaxResult issue(Long parkId, String sn, String cmd) {
        try {
            JSONObject baseObj = getBaseObj(sn, getServiceName(), getVersion());
            JSONArray ids = new JSONArray(1);
            ids.add(parkId);
            baseObj.put(CommandConstant.IDS, ids);
            JSONObject dtObj = new JSONObject();
            dtObj.put("plate", plate.get());
            dtObj.put("pk_serial", parkingSerial.get());
            dtObj.put("check_code", "1234");
            JSONObject dataObj = new JSONObject();
            dataObj.put(CommandConstant.IDS, ids);
            dataObj.put(CommandConstant.DT, dtObj);
            baseObj.put(CommandConstant.DATA, dataObj);

            @SuppressWarnings("unchecked")
            Map<String, Object> params = JSON.toJavaObject(baseObj, Map.class);

            AjaxResult issueResult = parkIpcCommandApi.issue(params);

            log.info("[停车系统]无牌车入场命令下发，服务名：{}，版本号：{}，车场ID：{}，设备编号：{}，下发参数：{}，下发结果：{}",
                    getServiceName(), getVersion(), parkId, sn, params, issueResult);

            updateCommonInfo(cmd, params, issueResult);

            return issueResult;
        } finally {
            close();
        }
    }

    public void setPlate(String plate) {
        this.plate.set(plate);
    }

    public void setParkingSerial(String parkingSerial) {
        this.parkingSerial.set(parkingSerial);
    }

    private void close() {
        plate.remove();
        parkingSerial.remove();
    }
}
